package me.techbird.nve.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 对需要登录的页面进行过滤拦截
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        String currentURL = req.getRequestURI();
        String contextPath = req.getContextPath();
        String targetURL = currentURL.substring(contextPath.length());
        HttpSession session = req.getSession(false);

        if((currentURL.contains("report.html") || (currentURL.contains("result.html")) || currentURL.contains("test.html")) && !((contextPath+"/login.html").equals(currentURL))){
            //不是登录页面判断用户session是否存在
            if(session == null || session.getAttribute("user") == null){
                resp.sendRedirect(contextPath+"/login.html");
            }else{
                chain.doFilter(req, resp);
            }
        }else if(currentURL.equals("/net-virtual-test/")){
            resp.sendRedirect(contextPath+"/index.html");
        }else{
            System.out.println("----session----："+session);
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
